package com.vortex.cloud.sample.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vortex.cloud.sample.domain.TaskUser;
import com.vortex.cloud.sample.dto.TaskUserExcelDTO;
import com.vortex.cloud.sample.mapper.CommonMapper;
import com.vortex.cloud.sample.mapper.TaskUserMapper;
import com.vortex.cloud.sample.service.CommonService;
import com.vortex.cloud.sample.service.TaskUserService;
import com.vortex.cloud.sample.vo.TaskUserVo;
import com.vortex.cloud.vfs.lite.base.dto.RestResultDTO;
import com.vortex.cloud.vfs.lite.base.util.ExcelUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-10-14 周四
 * @time 17:00
 * @description
 */
@Service
public class CommonServiceImpl extends ServiceImpl<CommonMapper, TaskUser> implements CommonService {

    @Resource
    private CommonService commonService;

    @Override
    public RestResultDTO<String> exportExcel(HttpServletResponse response) throws IOException {
        //获取所有用户信息
        List<TaskUser> userList = commonService.getBaseMapper().selectList(null);
        List<TaskUserExcelDTO> taskVOList = userList.stream().map(entity -> {
            TaskUserExcelDTO vo = new TaskUserExcelDTO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList());
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("TaskUser用户数据表.xls", "UTF-8"));
        response.setContentType("multipart/form-data");
        for (TaskUserExcelDTO user : taskVOList) {
            System.out.println(user + "----------------------------------");
        }
        this.writeExcel(response, taskVOList);
        return RestResultDTO.newSuccess("导出成功");
    }

    @Override
    public RestResultDTO<String> importExcel(MultipartFile file) throws IOException {
        List<TaskUserExcelDTO> dtoList = this.readExcel(file);
        for (TaskUserExcelDTO excelData : dtoList) {
            System.out.println(excelData);
        }

        List<TaskUser> taskUserList = dtoList.stream().map(entiy -> {
            TaskUser taskUser = new TaskUser();
            // 把 第一个类的字段 复制到 第二类的字段上
            BeanUtils.copyProperties(entiy, taskUser);
            taskUser.setCreateBy("王林");
            taskUser.setUpdateBy("王林");
            return taskUser;
        }).collect(Collectors.toList());

        if (!commonService.saveBatch(taskUserList)) {
            return RestResultDTO.newSuccess("文件导入失败!!!");
        }
        return RestResultDTO.newSuccess("文件导入成功");
    }

    /**
     * @Description: 读取 excel 数据
     * @Param: [response, list]
     * @return: void
     * @Author: 王林
     * @Date: 2021/10/14
     */
    public void writeExcel(HttpServletResponse response, List<TaskUserExcelDTO> list) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        //定义工作表对象
        WriteSheet sheet = EasyExcel.writerSheet(0, "用户数据表").head(TaskUserExcelDTO.class).build();
        //往 excel 中写入数据
        excelWriter.write(list, sheet);
        //关闭输出流
        excelWriter.finish();
    }

    /**
     * @Description: 读取 excel 文件数据
     * @Param: [file]
     * @return: java.util.List<com.vortex.cloud.sample.dto.TaskUserExcelDTO>
     * @Author: 王林
     * @Date: 2021/10/15
     */
    public List<TaskUserExcelDTO> readExcel(MultipartFile file) throws IOException {
        InputStream in = new BufferedInputStream(file.getInputStream());
        List<TaskUserExcelDTO> list = new LinkedList<>();
        EasyExcel.read(in)
                //把解析的实体类传进来ExcelData 实体类型，默认是 LinkedList
                .head(TaskUserExcelDTO.class)
                .sheet(0)
                .registerReadListener(new AnalysisEventListener<TaskUserExcelDTO>() {
                    @Override
                    public void invoke(TaskUserExcelDTO excelData, AnalysisContext analysisContext) {
                        list.add(excelData);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        //通知文件读取完毕
                        System.out.println("文件读取完毕!!!");
                    }
                }).doRead();
        return list;
    }
}
